package com.frikinet.tools.gui;

import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.InputStream;

import org.apache.commons.digester.Digester;

import com.frikinet.tools.i18n.FI18N;

public class FToolBarBuilder
{
	private FI18N i18n = null;
	private ActionListener listener = null;
	
	public FToolBarBuilder(ActionListener listener, FI18N i18n)
	{
		this.listener = listener;
		this.i18n = i18n;
	}
	
	public <T> T build(String xml, Class<T> clazz)
	{
		try
		{
			return build(new FileInputStream(xml), clazz);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}
	
	@SuppressWarnings("unchecked")
	public <T> T build(InputStream stream, Class<T> clazz)
	{
		Digester digester = getDigester();
		T bar = null;
		
		try
		{
			bar = (T)digester.parse(stream);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		return bar;
	}
	
	@SuppressWarnings({ "rawtypes" })
	private Digester getDigester()
	{
		Digester digester = new Digester();
		
		Class[] paramFI18N = {FI18N.class};
		Class[] paramActionListener = {ActionListener.class};
		
		digester.addObjectCreate("toolbar", FToolBar.class);
		digester.addCallMethod("toolbar", "setI18N", 1, paramFI18N);
		digester.addObjectParam("toolbar", 0, i18n);
		digester.addSetProperties("toolbar", "name", "name");
		
		digester.addObjectCreate("*/button", FButton.class);
		digester.addCallMethod("*/button", "setI18N", 1, paramFI18N);
		digester.addObjectParam("*/button", 0, i18n);
		digester.addCallMethod("*/button", "addActionListener", 1, paramActionListener);
		digester.addObjectParam("*/button", 0, listener);
		digester.addSetProperties("*/button","name","text");
		digester.addSetProperties("*/button", "resourceIcon", "resourceIcon");
		digester.addBeanPropertySetter("*/button/actionCommand", "actionCommand");
		digester.addBeanPropertySetter("*/button/tooltip", "toolTipText");
		digester.addSetNext("*/button", "add");
		
		return digester;
	}
}
